#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
从Unity项目中提取所有中文字符的脚本
用于生成TextMeshPro SDF字体时的字符集
"""

import re
import os
import codecs
from pathlib import Path

def is_chinese_char(char):
    """判断是否为中文字符"""
    return '\u4e00' <= char <= '\u9fff'

def is_useful_char(char):
    """判断是否为有用的字符（中文、数字、英文、常用符号）"""
    # 中文字符
    if is_chinese_char(char):
        return True
    
    # 数字
    if '0' <= char <= '9':
        return True
    
    # 英文字母
    if ('a' <= char <= 'z') or ('A' <= char <= 'Z'):
        return True
    
    # 常用标点符号和特殊字符
    useful_symbols = set('.,;:!?()[]{}+-*/=<>@#$%^&_|\\~`"\' \t\n\r，。；：！？（）【】｛｝＋－×÷＝＜＞％＆＿｜～｀""''')
    if char in useful_symbols:
        return True
    
    return False

def extract_useful_from_text(text):
    """从文本中提取有用字符"""
    useful_chars = set()
    for char in text:
        if is_useful_char(char):
            useful_chars.add(char)
    return useful_chars

def extract_useful_from_unicode_escape(text):
    """从Unicode转义序列中提取有用字符"""
    useful_chars = set()
    # 匹配 \uXXXX 格式的Unicode转义序列
    unicode_patterns = re.findall(r'\\u[0-9a-fA-F]{4}', text)
    
    for pattern in unicode_patterns:
        try:
            # 解码Unicode转义序列
            decoded_char = codecs.decode(pattern, 'unicode_escape')
            if is_useful_char(decoded_char):
                useful_chars.add(decoded_char)
        except:
            continue
    
    return useful_chars

def scan_file(file_path):
    """扫描单个文件中的有用字符"""
    useful_chars = set()
    
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
            
        # 提取直接的有用字符
        useful_chars.update(extract_useful_from_text(content))
        
        # 提取Unicode转义序列中的有用字符
        useful_chars.update(extract_useful_from_unicode_escape(content))
        
    except Exception as e:
        print(f"读取文件失败 {file_path}: {e}")
    
    return useful_chars

def scan_directory(directory, file_extensions):
    """扫描目录中指定扩展名的文件"""
    all_useful_chars = set()
    file_count = 0
    
    for ext in file_extensions:
        pattern = f"**/*{ext}"
        for file_path in Path(directory).glob(pattern):
            if file_path.is_file():
                chars = scan_file(file_path)
                all_useful_chars.update(chars)
                file_count += 1
                if chars:
                    chinese_count = sum(1 for c in chars if is_chinese_char(c))
                    if chinese_count > 0:
                        print(f"发现 {len(chars)} 个字符（{chinese_count}个中文）在: {file_path}")
    
    print(f"\n总共扫描了 {file_count} 个文件")
    return all_useful_chars

def categorize_characters(chars):
    """将字符分类"""
    chinese = set()
    numbers = set()
    letters = set()
    symbols = set()
    
    for char in chars:
        if is_chinese_char(char):
            chinese.add(char)
        elif '0' <= char <= '9':
            numbers.add(char)
        elif ('a' <= char <= 'z') or ('A' <= char <= 'Z'):
            letters.add(char)
        else:
            symbols.add(char)
    
    return chinese, numbers, letters, symbols

def main():
    """主函数"""
    print("=== Unity项目字符提取工具（包含数字、英文、符号）===\n")
    
    # 要扫描的文件类型
    file_extensions = ['.prefab', '.unity', '.cs', '.txt', '.json', '.xml']
    
    # 扫描Assets目录
    assets_dir = "Assets"
    if not os.path.exists(assets_dir):
        print(f"错误: {assets_dir} 目录不存在")
        return
    
    print(f"开始扫描 {assets_dir} 目录...")
    print(f"扫描文件类型: {', '.join(file_extensions)}\n")
    
    useful_chars = scan_directory(assets_dir, file_extensions)
    
    if not useful_chars:
        print("未发现任何有用字符")
        return
    
    # 分类字符
    chinese, numbers, letters, symbols = categorize_characters(useful_chars)
    
    # 按类别排序
    sorted_chinese = sorted(chinese)
    sorted_numbers = sorted(numbers)
    sorted_letters = sorted(letters)
    sorted_symbols = sorted(symbols)
    
    # 合并所有字符（按类别顺序：数字、字母、中文、符号）
    all_sorted_chars = sorted_numbers + sorted_letters + sorted_chinese + sorted_symbols
    
    print(f"\n=== 提取结果 ===")
    print(f"数字: {len(sorted_numbers)} 个 - {''.join(sorted_numbers)}")
    print(f"字母: {len(sorted_letters)} 个 - {''.join(sorted_letters)}")
    print(f"中文: {len(sorted_chinese)} 个")
    print(f"符号: {len(sorted_symbols)} 个")
    print(f"总计: {len(all_sorted_chars)} 个字符")
    print()
    
    # 输出中文字符列表（每行50个字符）
    print("中文字符列表:")
    for i in range(0, len(sorted_chinese), 50):
        line_chars = sorted_chinese[i:i+50]
        print(''.join(line_chars))
    
    # 保存到文件
    output_file = "all_characters_for_sdf.txt"
    with open(output_file, 'w', encoding='utf-8') as f:
        # 写入连续的字符串（用于TextMeshPro）
        f.write(''.join(all_sorted_chars))
        f.write('\n\n')
        
        # 写入详细信息
        f.write(f"总字符数: {len(all_sorted_chars)}\n")
        f.write(f"数字({len(sorted_numbers)}个): {''.join(sorted_numbers)}\n")
        f.write(f"字母({len(sorted_letters)}个): {''.join(sorted_letters)}\n")
        f.write(f"中文({len(sorted_chinese)}个):\n")
        for i in range(0, len(sorted_chinese), 50):
            line_chars = sorted_chinese[i:i+50]
            f.write(''.join(line_chars) + '\n')
        f.write(f"符号({len(sorted_symbols)}个): {''.join(sorted_symbols)}\n")
    
    print(f"\n完整字符集已保存到: {output_file}")
    print("您可以将文件中的字符串复制到TextMeshPro Font Asset Creator的Custom Character List中")
    
    # 输出一些统计信息
    print(f"\n=== 统计信息 ===")
    print(f"字符总数: {len(all_sorted_chars)}")
    print(f"建议Atlas分辨率: {'4096x4096' if len(all_sorted_chars) > 2000 else '2048x2048'}")
    print(f"建议Padding: 5-9")
    print(f"建议Point Size: 90-120")

if __name__ == "__main__":
    main() 